<template>
	<view class="container">
		<text class="text">正在跳转，请稍候...</text>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				
			}
		},
		onLoad(options) {
			if(options.no){
				this.redirectCode(options.no);
			}else{
				this.gotoPay();
			}
		},
		methods: {
			//获取URL参数
			getUrlParam(name){
				var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)');
				let url = window.location.href.split('#')[0];
				let search = url.split('?')[1];
				if(search){
					var r = search.substr(0).match(reg);
					if (r !== null) return unescape(r[2]);
					return null
				}else{
					return null
				}
			},
			//跳转获取CODE的URI链接
			async redirectCode(no){
				let _this = this;
				let href = `${window.location.protocol}//${window.location.host}/#/pages/payment/authorize`;
				let uri = encodeURIComponent(href);
				//调用获取授权接口
				_this.$api.request({
					url: `/wechatpay/oauth`,
					method: "post",
					data: {
						outTradeNo: no,
						redirectUri: uri
					}
				}).then(res=>{
					window.location.href = res.data.url;
				});
			},
			//获取CODE及调用下单接口
			async gotoPay(){
				let _this = this;
				let code = _this.getUrlParam('code'); //Code
				let tradeNo = _this.getUrlParam('state'); //订单号
				//console.log(code);
				//如果拿到code，调用下单接口
				if(!code || !tradeNo){
					_this.$api.msg("获取授权Code失败，请重试");
					return
			    }
				//调用统一下单接口
				_this.$api.request({
					url: `/wechatpay`,
					method: "post",
					data: {
						outTradeNo: tradeNo,
						description: '交易订单',
						code: code,
					}
				}).then(res=>{
					//调起微信浏览JS支付
					WeixinJSBridge.invoke('getBrandWCPayRequest', {
						"appId": res.data.appId,
						"timeStamp": res.data.timeStamp,
						"nonceStr": res.data.nonceStr,
						"package": res.data.package,
						"signType": res.data.signType,
						"paySign": res.data.paySign
					},
					function(resPay){
						//resPay.err_msg将在用户支付成功后返回ok
						if(resPay.err_msg == "get_brand_wcpay_request:ok" ){
							uni.redirectTo({
								url: `success?no=${tradeNo}`
							});
						}else{
							uni.showModal({
								title: '错误提示',
								showCancel: false,
								confirmText: '返回',
								content: '支付失败：'+resPay.err_msg,
								success(res) {
									if (res.confirm) {
										uni.navigateBack();
									}
							    }
							});
						}
					});
				});
			},
		}
	}
</script>

<style lang="scss">
	.text{
		position: absolute;
		top: 50%;
		left: 0;
		right: 0;
		margin-top: -12rpx;
		color: #999;
		font-size: 28rpx;
		line-height: 1;
		text-align: center;
	}
</style>